<template>
    <div class="user-list">
        <div class="toolbar">
            <el-input
                v-model="searchKeyword"
                placeholder="请输入用户名称搜索"
                clearable
                @input="handleSearch"
                style="width: 300px"
            >
                <template #prefix>
                    <el-icon><Search /></el-icon>
                </template>
            </el-input>
            <el-button type="primary" @click="handleAdd">新增用户</el-button>
        </div>

        <el-table
            :data="userList"
            style="width: 100%"
            v-loading="loading"
        >
            <el-table-column prop="account" label="账号" />
            <el-table-column prop="nickName" label="昵称" />
            <el-table-column prop="phone" label="手机号" />
            <el-table-column prop="sex" label="性别" width="80" />
            <el-table-column prop="roleName" label="角色" />
            <el-table-column prop="points" label="积分" width="80" />
            <el-table-column prop="disable" label="状态" width="80">
                <template #default="{ row }">
                    <el-tag :type="row.disable === 1 ? 'success' : 'danger'">
                        {{ row.disable === 1 ? '启用' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间" width="180" />
            <el-table-column label="操作" width="280" fixed="right">
                <template #default="{ row }">
                    <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
                    <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
                    <el-button link type="primary" @click="handlePoint(row)">积分操作</el-button>
                    <el-button 
                        link 
                        :type="row.disable === 1 ? 'danger' : 'success'"
                        @click="handleDisable(row)"
                    >
                        {{ row.disable === 1 ? '禁用' : '启用' }}
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <div class="pagination-container">
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="total"
                layout="total, sizes, prev, pager, next"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>

        <user-form
            v-model="dialogVisible"
            :type="dialogType"
            :user-data="currentUser"
            :role-list="roleList"
            @success="handleSuccess"
        />

        <el-dialog
            v-model="pointDialogVisible"
            title="积分操作"
            width="30%"
        >
            <el-form :model="pointForm" label-width="100px">
                <el-form-item label="操作方式">
                    <el-select v-model="pointForm.way" placeholder="请选择操作方式">
                        <el-option :label="'增加'" :value="1" />
                        <el-option :label="'减少'" :value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item label="积分值">
                    <el-input-number 
                        v-model="pointForm.point" 
                        :min="1" 
                        :precision="0"
                        placeholder="请输入积分值" 
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handlePointClose">取消</el-button>
                    <el-button type="primary" @click="handlePointSubmit">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { List as GetList, Delete, details, Pint, disable, type User } from '@/apis/user'
import { List as GetRoleList, type UserRole } from '@/apis/role'
import UserForm from './UserForm.vue'

// 状态变量
const loading = ref(false)
const dialogVisible = ref(false)
const pointDialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const currentUser = ref<User>()
const userList = ref<User[]>([])
const roleList = ref<UserRole[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchKeyword = ref('')

// 积分操作表单
const pointForm = ref({
    way: 1,
    point: 1,
    userUuid: ''
})

// 获取角色列表
const fetchRoleList = async () => {
    try {
        const data = await GetRoleList({
            keyword: ''
        })
        roleList.value = (data.list|| []).filter(r => r.roleStatus === 1)
    } catch (error) {
        console.error('获取角色列表失败:', error)
        ElMessage.error('获取角色列表失败')
    }
}

// 获取用户列表
const fetchList = async () => {
    loading.value = true
    try {
        const data = await GetList({
            page: currentPage.value,
            pageSize: pageSize.value,
            keyword: searchKeyword.value.trim()
        })
        userList.value = data.list
        total.value = data.total
    } catch (error) {
        console.error('获取用户列表失败:', error)
        ElMessage.error('获取用户列表失败')
    } finally {
        loading.value = false
    }
}

// 搜索处理
let searchTimer: NodeJS.Timeout | null = null
const handleSearch = () => {
    if (searchTimer) {
        clearTimeout(searchTimer)
    }
    searchTimer = setTimeout(() => {
        currentPage.value = 1 // 重置码
        fetchList()
    }, 300)
}

// 新增用户
const handleAdd = () => {
    dialogType.value = 'add'
    currentUser.value = undefined
    dialogVisible.value = true
}

// 编辑用户
const handleEdit = async (row: User) => {
    dialogType.value = 'edit'
    try {
        const detail = await details(row.uUID)
        currentUser.value = detail
        dialogVisible.value = true
    } catch (error) {
        console.error('获取用户详情失败:', error)
        ElMessage.error('获取用户详情失败')
    }
}

// 删除用户
const handleDelete = async (row: User) => {
    try {
        await ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
            type: 'warning'
        })
        await Delete(row.uUID)
        ElMessage.success('删除成功')
        fetchList()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error)
            ElMessage.error('删除失败')
        }
    }
}

// 禁用/启用用户
const handleDisable = async (row: User) => {
    const isDisable = row.disable === 1
    try {
        await ElMessageBox.confirm(
            `确定要${isDisable ? '禁用' : '启用'}该用户吗？`, 
            '提示',
            {
                type: 'warning'
            }
        )
        await disable({
            uuid: row.uUID,
            status: isDisable ? 2 : 1
        })
        ElMessage.success(`${isDisable ? '禁用' : '启用'}成功`)
        fetchList()
    } catch (error) {
        if (error !== 'cancel') {
            console.error(`${isDisable ? '禁用' : '启用'}失败:`, error)
            ElMessage.error(`${isDisable ? '禁用' : '启用'}失败`)
        }
    }
}

// 分页处理
const handleSizeChange = (val: number) => {
    pageSize.value = val
    fetchList()
}

const handleCurrentChange = (val: number) => {
    currentPage.value = val
    fetchList()
}

// 操作成功回调
const handleSuccess = () => {
    fetchList()
}

// 积分操作
const handlePoint = (row: User) => {
    pointForm.value = {
        way: 1,
        point: 1,
        userUuid: row.uUID
    }
    pointDialogVisible.value = true
}

// 关闭积分对话框
const handlePointClose = () => {
    pointDialogVisible.value = false
    pointForm.value = {
        way: 1,
        point: 1,
        userUuid: ''
    }
}

// 积分操作提交
const handlePointSubmit = async () => {
    try {
        await Pint({
            way: pointForm.value.way,
            point: pointForm.value.point,
            userUuid: pointForm.value.userUuid
        })
        ElMessage.success('积分操作成功')
        pointDialogVisible.value = false
        fetchList()
    } catch (error) {
        console.error('积分操作失败:', error)
        ElMessage.error('积分操作失败')
    }
}

// 初始化
onMounted(() => {
    fetchRoleList()
    fetchList()
})
</script>

<style scoped lang="scss">
.user-list {
    .toolbar {
        margin-bottom: 16px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .pagination-container {
        margin-top: 16px;
        display: flex;
        justify-content: flex-end;
    }
}
</style> 